package com.qingzhu.controller.shopserver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingzhu.pojo.ShopCart;
import com.qingzhu.pojo.ShopOption;
import com.qingzhu.pojovo.ResultVo;
import com.qingzhu.service.ShopOptionService;
import com.qingzhu.service.impl.ShopOptionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

@WebServlet("/cart/remove")
public class RemoveCartController extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    ShopOptionService shopOptionService = new ShopOptionServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("移除购物车选项服务..");
        String itemId = req.getParameter("itemId");

        // 获取token信息（最新方案）
        String token = req.getHeader("token");
        token = URLDecoder.decode(token,"UTF-8");
        token = token.substring(1,token.length()-1);

        // 获取cookie信息（弃用方案）
        Cookie[] cookies = req.getCookies();

        // 如果前台没有验证信息传递过来或者购物车已经被清空，就直接响应1002（兼容cookie技术）
        if (cookies == null || cookies[0].getValue() == "") {
            if (token.equals("null") == true) {
                resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(1002,"未检测到购物车")));
            }else {
                System.out.println("检测到浏览器对cookie的支持可能不稳定...将自动切换到token技术");
                // 将购物车反序列化
                ShopCart shopCart = objectMapper.readValue(token, ShopCart.class);
                if (itemId.equals("-1")) {
                    System.out.println("正在清空购物车...");
                    resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(1000,"购物车空空的哦~，去看看心仪的商品吧~")));
                }else {
                    System.out.println("正在移除购物车选项...");
                    ShopCart cart = removeCart(shopCart, Integer.parseInt(itemId));
                    ResultVo resultVo = cart.getShopOptions() != null && cart.getShopOptions().size() != 0 ?
                            new ResultVo(200,shopCart):
                            new ResultVo(1000,"购物车空空的哦~，去看看心仪的商品吧~");
                    resp.getWriter().write(objectMapper.writeValueAsString(resultVo));
                }
            }
        }else {
            String cartJson = cookies[0].getValue();
            // 解析购物车信息
            String decode = URLDecoder.decode(cartJson, "UTF-8");
            // 将购物车反序列化
            ShopCart shopCart = objectMapper.readValue(decode, ShopCart.class);
//            List<ShopOption> shopCart = objectMapper.readValue(decode, new TypeReference<List<ShopOption>>(){});
            if (itemId.equals("-1")) {
                System.out.println("正在清空购物车...");
                // 清空购物车
                Cookie cookie = new Cookie("cart", null);
                resp.addCookie(cookie);
                resp.getWriter().write(objectMapper.writeValueAsString(new ResultVo(1000,"购物车空空的哦~，去看看心仪的商品吧~")));
            }else {
                System.out.println("正在移除购物车选项...");
                ShopCart cart = removeCart(shopCart, Integer.parseInt(itemId));
                // 更新cookie
                updateCookie(resp,cart);
            }
        }
    }

    // 处理购物车选项
    public ShopCart removeCart(ShopCart shopCart,int itemId) {
        // 修改购物车选项列表
        shopCart = shopOptionService.removeShopSption(shopCart, itemId);
        // 如果仍然存在商品，则走更新流程
        if (shopCart.getShopOptions().size() != 0) {
            // 更新购物车信息
            shopCart = shopOptionService.updateShopSption(shopCart);
        }
        return shopCart;
    }
    /* 更新cookie 如果购物车是空的则返回1000 */
    public void updateCookie (HttpServletResponse resp, ShopCart shopCart) throws IOException {
        // 将购物车序列化成json串
        String cartJson = objectMapper.writeValueAsString(shopCart);
        // 将购物车的信息编码后再储存，否则可能会抛出不合法的字符异常
        String encodeCart = URLEncoder.encode(cartJson, "UTF-8");
        /* 更新cookie */
        Cookie cookie = new Cookie("cart", encodeCart);
        resp.addCookie(cookie);
        ResultVo resultVo = shopCart.getShopOptions() != null && shopCart.getShopOptions().size() != 0 ?
                new ResultVo(200,shopCart):
                new ResultVo(1000,"购物车空空的哦~，去看看心仪的商品吧~");
        resp.getWriter().write(objectMapper.writeValueAsString(resultVo));
    }
}
